package com.etc.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.etc.entity.MusicStyle;
import com.etc.entity.PageInfo;
import com.etc.entity.Region;
import com.etc.entity.Singger;
import com.etc.service.SinggerService;
import com.etc.service.impl.SinggerServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Servlet implementation class SingerInfoServlet
 */
@WebServlet("/SingerInfo")
@MultipartConfig
public class SingerInfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private SinggerService singgerService = new SinggerServiceImpl();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SingerInfoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String op = request.getParameter("op");
		if ("detail".equals(op)) {
			doFindById(request, response);
		} else if ("deleteById".equals(op)) {
			doDeleteById(request, response);
		} else if ("add".equals(op)) {
			doAddSinger(request, response);
		} else if ("pageByCondition".equals(op)) {
			doPageByCondition(request, response);
		} else if ("modify".equals(op)) {
			doModify(request, response);
		} else if ("export".equals(op)) {
			doExport(request, response);
		}
	}

	private void doExport(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HSSFWorkbook wb = new HSSFWorkbook();
		//建立新的sheet对象（excel的表单）
		HSSFSheet sheet=wb.createSheet("歌手表");
		
		List<String[]> list = new ArrayList<String[]>();
		String[] rows = new String[]{"歌手编号","歌手名","头像名称","歌手风格","性别","生日","所属地区","职业","国籍","出生地"};  
        list.add(rows);
        for (int i = 0; i < list.size(); i++) {
        	HSSFRow row = null;
        	if(i==1){
        		row = sheet.createRow(2);
        	}else{
        		row = sheet.createRow(i);
        	}
        	String[] rowsName = list.get(i);
			for(int c = 0;c<rowsName.length;c++){
				HSSFCell cell = row.createCell(c);
				cell.setCellValue(rowsName[c]);
			}
		}
        List<Object[]>  dataList = new ArrayList<Object[]>();  
        Object[] objs = null; 
        
        List<Singger> mylist = singgerService.exportAllSingerInfo();
        for (int i = 0; i < mylist .size(); i++) {  
        	Singger singger = mylist.get(i);  
            objs = new Object[rows.length];  
            objs[0] = singger.getSinggerId();
            objs[1] = singger.getSinggerName();
            objs[2] = singger.getSinggerImgPath();
            objs[3] = singger.getMusicStyle().getStyleName();
            objs[4] = singger.getGender();
            objs[5] = singger.getBirthday();
            objs[6] = singger.getRegion().getRegionName();
            objs[7] = singger.getOccupation();
            objs[8] = singger.getNationality();
            objs[9] = singger.getBirthplace();
            dataList.add(objs);  
        }
        for(int i = 0; i < dataList.size(); i++) {
        	HSSFRow row =sheet.createRow(i+1);
        	Object[] objsRow = dataList.get(i);
        	int length = 0;
        	for (int j = 0; j < objsRow.length; j++) {
				HSSFCell cell = row.createCell(j);
				if(objsRow[j]!=null && !objsRow[j].toString().isEmpty()){
					if(objsRow[j].toString().length()>length){
						//获取本列最高的字符长度
						length =  objsRow[j].toString().length();
					}
					cell.setCellValue(objsRow[j].toString());
				}
			}
		}
        OutputStream output=response.getOutputStream();
		response.reset();
		response.setHeader("Content-disposition", "attachment; filename=details.xls");
		response.setContentType("application/msexcel");
		wb.write(output);
		output.close();
		
	}

	private void doModify(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		response.setContentType("text/plain;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		   Integer singgerId = Integer.parseInt(request.getParameter("singgerId"));
		   String singgerName = request.getParameter("singgerName");
		   Integer styleId = Integer.parseInt(request.getParameter("musicStyle"));
		   Integer gender = Integer.parseInt(request.getParameter("gender"));
		   String birthday = request.getParameter("birthday");
		   Integer regionId = Integer.parseInt(request.getParameter("region"));
		   String occupation = request.getParameter("occupation");
		   String nationality = request.getParameter("nationality"); 
		   String birthplace = request.getParameter("birthplace");
		   Part part = request.getPart("singgerImgPath");
		   
		   Singger singger = new Singger();
		   singger.setSinggerId(singgerId);
		   singger.setSinggerName(singgerName);
		   MusicStyle musicStyle = new MusicStyle();
		   musicStyle.setStyleId(styleId);
		   singger.setMusicStyle(musicStyle);
		   singger.setGender(gender);
		   singger.setBirthday(birthday);
		   Region region = new Region();
		   region.setRegionId(regionId);
		   singger.setRegion(region);
		   singger.setOccupation(occupation);
		   singger.setNationality(nationality);
		   singger.setBirthplace(birthplace);
		// 判断文件是否上传
			if (part.getSize() != 0) {
				
				// 1.对上传的文件进行MIME类型判断
				String allowImgContentType = "image/jpg,image/jpeg,image/png,image/gif";
				// 获取上传文件的内容类型
				String fileContentType = part.getContentType();
							
				if (allowImgContentType.indexOf(fileContentType) == -1) {
						// 响应结果文件类型不匹配
						out.print("文件类型不匹配,支持image/jpg,image/jpeg,image/png,image/gif!");
						return;
				}else if(part.getSize() > 40000) {
						// 响应结果文件大小不匹配
						out.print("图片大小不能超过40K!");
						return;
				}else {
								
						// 获取原文件名
						String realFileName  = part.getSubmittedFileName(); // QQ.jpg
						// 获取原文件名的拓展名
						String fileSuffix =  realFileName.substring(realFileName.lastIndexOf("."));
						// 存储文件名,保证文件名唯一
						// 时间戳+4位随机数  或 时间戳+4位随机数+原文件名
						StringBuilder fileName = new StringBuilder();
						// 时间戳
						LocalDateTime now = LocalDateTime.now();
						DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
						String time = dateTimeFormatter.format(now);
						// 4位随机数
						int random = (int) ((Math.random() * 9 + 1) * 1000); // 1000-9999
					    // 拼接方式1: 没有保留原文件名
					    fileName.append(time).append(random).append(fileSuffix);  // 202106101704125727.jpg
						// 关联文件存储的目录
						File file = new File("D:\\file\\img"); 
						// 定义文件路径
						StringBuilder filePath = new StringBuilder();
						filePath.append(file).append(File.separator).append(fileName);
						// 将文件写入指定位置
						part.write(filePath.toString());
						// 商品对象设置图片路径属性,数据库存储仅是文件名
						singger.setSinggerImgPath(fileName.toString());
				}
			} /*
				 * else { // 无文件,采用默认图片 singger.setSinggerImgPath("default-goods-img.jpg"); }
				 */
			// 调用业务层
			boolean flag = singgerService.modifySingerInfo(singger);
			
			if (flag) {
				// 响应成功结果
				out.print("歌手修改成功");
			}
		
	}

	private void doPageByCondition(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		String singgerName = request.getParameter("singgerName");
		String pageNum = request.getParameter("pageNum");
		String pageSize = request.getParameter("pageSize");
		PageInfo<Singger> pageInfo = singgerService.getSingerInfoBySingerName(singgerName,Integer.parseInt(pageNum), Integer.parseInt(pageSize));
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(pageInfo);
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.write(json);
		
	}

	private void doAddSinger(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		response.setContentType("text/plain;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		   String singgerName = request.getParameter("singgerName");
		   Integer styleId = Integer.parseInt(request.getParameter("musicStyle"));
		   Integer gender = Integer.parseInt(request.getParameter("gender"));
		   String birthday = request.getParameter("birthday");
		   Integer regionId = Integer.parseInt(request.getParameter("region"));
		   String occupation = request.getParameter("occupation");
		   String nationality = request.getParameter("nationality"); 
		   String birthplace = request.getParameter("birthplace");
		   Part part = request.getPart("singgerImgPath");
		   
		   Singger singger = new Singger();
		   singger.setSinggerName(singgerName);
		   MusicStyle musicStyle = new MusicStyle();
		   musicStyle.setStyleId(styleId);
		   singger.setMusicStyle(musicStyle);
		   singger.setGender(gender);
		   singger.setBirthday(birthday);
		   Region region = new Region();
		   region.setRegionId(regionId);
		   singger.setRegion(region);
		   singger.setOccupation(occupation);
		   singger.setNationality(nationality);
		   singger.setBirthplace(birthplace);
		// 判断文件是否上传
			if (part.getSize() != 0) {
				
				// 1.对上传的文件进行MIME类型判断
				String allowImgContentType = "image/jpg,image/jpeg,image/png,image/gif";
				// 获取上传文件的内容类型
				String fileContentType = part.getContentType();
							
				if (allowImgContentType.indexOf(fileContentType) == -1) {
						// 响应结果文件类型不匹配
						out.print("文件类型不匹配,支持image/jpg,image/jpeg,image/png,image/gif!");
						return;
				}else if(part.getSize() > 40000) {
						// 响应结果文件大小不匹配
						out.print("图片大小不能超过40K!");
						return;
				}else {
								
						// 获取原文件名
						String realFileName  = part.getSubmittedFileName(); // QQ.jpg
						// 获取原文件名的拓展名
						String fileSuffix =  realFileName.substring(realFileName.lastIndexOf("."));
						// 存储文件名,保证文件名唯一
						// 时间戳+4位随机数  或 时间戳+4位随机数+原文件名
						StringBuilder fileName = new StringBuilder();
						// 时间戳
						LocalDateTime now = LocalDateTime.now();
						DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
						String time = dateTimeFormatter.format(now);
						// 4位随机数
						int random = (int) ((Math.random() * 9 + 1) * 1000); // 1000-9999
					    // 拼接方式1: 没有保留原文件名
					    fileName.append(time).append(random).append(fileSuffix);  // 202106101704125727.jpg
						// 关联文件存储的目录
						File file = new File("D:\\file\\img"); 
						// 定义文件路径
						StringBuilder filePath = new StringBuilder();
						filePath.append(file).append(File.separator).append(fileName);
						// 将文件写入指定位置
						part.write(filePath.toString());
						// 商品对象设置图片路径属性,数据库存储仅是文件名
						singger.setSinggerImgPath(fileName.toString());
				}
			}else {
				// 无文件,采用默认图片
				singger.setSinggerImgPath("default-goods-img.jpg");
			}
			
			// 调用业务层
			boolean flag = singgerService.addSinger(singger);
			
			if (flag) {
				// 响应成功结果
				out.print("歌手添加成功");
			}
		
	}

	private void doDeleteById(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Integer singgerId = Integer.parseInt(request.getParameter("singgerId"));
		boolean flag = singgerService.deleteSingerById(singgerId);
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(flag);
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.write(json);
		
	}

	private void doFindById(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Integer singgerId = Integer.parseInt(request.getParameter("singgerId"));
		Singger singger = singgerService.getSingerInfoById(singgerId);
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(singger);
		out.print(json);
	}

}
